<?php
/**
 * Created by PhpStorm.
 * User: nfangxu
 * Date: 2019/1/15
 * Time: 10:20
 */

namespace App\Services;


use Overtrue\EasySms\EasySms;

class SmsSender
{
    const USER_REGISTER = 1;
    const USER_LOGIN = 2;
    const PASSWORD_FORGET = 3;
    const PASSWORD_RESET = 4;

    const TEMPLATE = [
        self::USER_REGISTER => "SMS_152460548",
        self::USER_LOGIN => "SMS_152460548",
        self::PASSWORD_FORGET => "SMS_152460548",
        self::PASSWORD_RESET => "SMS_152460548",
    ];

    const TYPE_DESCRIPTION = [
        self::USER_REGISTER => "用户注册",
        self::USER_LOGIN => "用户登录",
        self::PASSWORD_FORGET => "找回密码",
        self::PASSWORD_RESET => "修改密码",
    ];


    private $sms;

    public function __construct()
    {
        $this->sms = new EasySms(config('services.sms'));
    }

    /**
     * @param $type
     * @param $mobile
     * @param $code
     * @return bool
     * @throws \Overtrue\EasySms\Exceptions\InvalidArgumentException
     */
    public function send($type, $mobile, $code)
    {
        $template = self::TEMPLATE[$type] ?? self::TEMPLATE[self::USER_REGISTER];

        try {
            $this->sms->send($mobile, [
                'template' => $template,
                'data' => [
                    'code' => $code
                ],
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $e) {
            logger('sms-send-failure', $e->getResults());
            return false;
        }

        return true;
    }
}